import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, register, logout, getCurrentUser, updateUserInfo, changePassword, changeName, uploadFile, updateAvatar } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('user') || '{}'))
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const userLogin = async (credentials) => {
    try {
      const response = await login(credentials)

      // 如果API返回了用户信息，直接使用
      if (response && response.user) {
        token.value = response.token
        userInfo.value = response.user
        localStorage.setItem('token', response.token)
        localStorage.setItem('user', JSON.stringify(response.user))
      } else {
        // 兼容旧版本API
        token.value = response
        localStorage.setItem('token', response)

        // 获取用户信息
        const user = await getCurrentUser()
        userInfo.value = user
        localStorage.setItem('user', JSON.stringify(user))
      }

      return response
    } catch (error) {
      throw error
    }
  }

  // 注册
  const userRegister = async (userData) => {
    try {
      const response = await register(userData)

      // 如果API返回了用户信息，直接使用
      if (response && response.user) {
        token.value = response.token
        userInfo.value = response.user
        localStorage.setItem('token', response.token)
        localStorage.setItem('user', JSON.stringify(response.user))
      } else {
        // 兼容旧版本API
        token.value = response
        localStorage.setItem('token', response)

        // 获取用户信息
        const user = await getCurrentUser()
        userInfo.value = user
        localStorage.setItem('user', JSON.stringify(user))
      }

      return response
    } catch (error) {
      throw error
    }
  }

  // 登出
  const userLogout = async () => {
    try {
      await logout()
      token.value = ''
      userInfo.value = {}
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    } catch (error) {
      // 即使登出失败也要清除本地状态
      token.value = ''
      userInfo.value = {}
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      throw error
    }
  }

  // 更新用户信息
  const updateUser = async (userData) => {
    try {
      const response = await updateUserInfo(userData)
      // 重新获取用户信息
      const user = await getCurrentUser()
      userInfo.value = user
      localStorage.setItem('user', JSON.stringify(user))
      return response
    } catch (error) {
      throw error
    }
  }

  // 修改密码
  const changeUserPassword = async (passwordData) => {
    try {
      const response = await changePassword(passwordData)
      return response
    } catch (error) {
      throw error
    }
  }

  // 修改用户名
  const changeUserName = async (newName) => {
    try {
      const response = await changeName(newName)
      // 修改成功后刷新用户信息
      const user = await getCurrentUser()
      userInfo.value = user
      localStorage.setItem('user', JSON.stringify(user))
      return response
    } catch (error) {
      throw error
    }
  }

  // 刷新用户信息
  const refreshUserInfo = async () => {
    try {
      if (isLoggedIn.value) {
        const user = await getCurrentUser()
        userInfo.value = user
        localStorage.setItem('user', JSON.stringify(user))
      }
    } catch (error) {
      console.warn('刷新用户信息失败:', error)
    }
  }

  // 上传头像
  const uploadUserAvatar = async (file) => {
    try {
      // 先上传文件
      const avatarUrl = await uploadFile(file)

      if (avatarUrl) {
        // 上传成功后更新用户头像
        await updateAvatar(avatarUrl)

        // 自动从后端刷新用户信息
        try {
          const freshUser = await getCurrentUser()
          userInfo.value = freshUser
          localStorage.setItem('user', JSON.stringify(freshUser))

          // 如果后端返回的用户信息中没有avatar字段，手动添加
          if (!freshUser.avatar) {
            freshUser.avatar = avatarUrl
            userInfo.value = freshUser
            localStorage.setItem('user', JSON.stringify(freshUser))
          }
        } catch (refreshError) {
          console.warn('刷新用户信息失败，使用上传的头像URL:', refreshError)
          // 如果刷新失败，至少更新本地头像信息
          if (userInfo.value) {
            userInfo.value.avatar = avatarUrl
            localStorage.setItem('user', JSON.stringify(userInfo.value))
          }
        }

        return avatarUrl
      } else {
        throw new Error('上传响应格式错误')
      }
    } catch (error) {
      throw error
    }
  }

  return {
    // 状态
    token,
    userInfo,
    isLoggedIn,
    // 方法
    userLogin,
    userRegister,
    userLogout,
    updateUser,
    changeUserPassword,
    changeUserName,
    refreshUserInfo,
    uploadUserAvatar
  }
})
